import {Upload, Icon, Modal, message} from 'antd';

import {uploadUrl} from "../../services/api";
import PropTypes from 'prop-types';
import Immutable, {Map, is} from 'immutable'


/**w
 *
 * @desc    把 antd 组件的图片上传组件封装在一起，
 *          只需要关心初始化的值 init 以及 onchang 方法。支持多个图片
 * @param   {Array} init 初始化的地址
 * @param   {func} onResult(data)  返回图片上传结果。
 * @param   {Int} num  设置图片上传个数。
 * @return
 */

class PUpLodadImg extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    fileList: [],
    ifInit: false,//是否加载完成初始化
  };

  static propTypes = {
    init: PropTypes.array,
    onResult: PropTypes.func,
    num: PropTypes.number
  }


  componentWillMount = () => {
    if (this.props.init) {
      if (Object.prototype.toString.call(this.props.init) == "[object Array]") {
        this.updataList(this.props.init);
      }
    }
  }

  componentWillReceiveProps = (nextProps) => {

    const nextInit = nextProps.init;
    const thisInit = this.props.init;
    if (this.state.ifInit) {
      return;
    }

    if (JSON.stringify(nextInit) !== JSON.stringify(thisInit)) {
      if (nextInit.length !== 0) {
        this.updataList(nextInit);
      }
    }
  }


  shouldComponentUpdate = (nextProps = {}, nextState = {}) => {
    const thisProps = this.props || {}, thisState = this.state || {};

    if (Object.keys(thisProps).length !== Object.keys(nextProps).length ||
      Object.keys(thisState).length !== Object.keys(nextState).length) {
      return true;
    }
    for (const key in nextProps) {
      if (thisProps[key] !== nextProps[key] || !is(thisProps[key], nextProps[key])) {
        return true;
      }
    }
    for (const key in nextState) {
      if (thisState[key] !== nextState[key] || !is(thisState[key], nextState[key])) {
        return true;
      }
    }
    return false;
  }

  //刷新
  updataList = (arr) => {
    const newArr = arr.filter(val => val.trim() !== "");
    if (newArr.length !== 0) {
      console.log(arr);
      let fileList = [...this.state.fileList];
      newArr.map((val, key) => {
        fileList.push({
          uid: key,
          url: val,
        })
      });
      this.setState({fileList, ifInit: true});
    }
  }

  handleCancel = () => this.setState({previewVisible: false})

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  handleChange = (info) => {

    let result = true;
    const status = info.file.status;

    //除了移除状态，上传过程中，判断是否符合上传规则
    if (status !== "removed") {
      result = this.beforeUpload(info.file);
    }
    if (!result) {
      return;
    }

    let fileList = [...this.state.fileList];
    fileList = info.fileList;
    this.setState({fileList});


    if (status !== 'uploading') {
      // console.log(info.file, info.fileList);
    }
    if (status === 'done') {
      console.log(info.file.response.data.filegroupid);
      // this.props.result("done", info.file.response.data.filegroupid);
      message.success(`${info.file.name} 文件上传成功。`);

      if (this.props.onResult) {
        if (info.fileList.length === 0) {
          return;
        }
        const result = info.fileList.reduce((acc, elem) => {
          if (elem.response && elem.response.data) {
            acc.push(elem.response.data)
            return acc;
          }
          if (elem.url) {
            acc.push(elem.url)
            return acc;
          }
        }, []);
        this.props.onResult(result);
      }


    } else if (status === 'error') {
      message.error(`${info.file.name} 文件上传失败。`);
    }
    if (info.file.status == "removed") {
      let result;
      //如果全部删除
      if (info.fileList.length === 0) {
        this.props.onResult([]);
        return;
      } else {
        //如果部分删除
        result = info.fileList.reduce((acc, elem) => {
          if (elem.url) {
            acc.push(elem.url);
            return acc;
          }
        }, []);
      }
      this.props.onResult(result);
    }
  }

  beforeUpload = (file) => {

    const types = ["image/png", "image/jpeg", "image/jpg"];
    console.log(file.type);

    if (types.indexOf(file.type) === -1) {
      message.error('只能上传图片!');
      return false;
    }
    const isLt3M = file.size / 1024 / 1024 < 3;
    if (!isLt3M) {
      message.error('图片大小大于3MB!');
      return false;
    }
    return true;
    // return isJPG && isPNG && isLt3M;
  };


  render() {
    const {previewVisible, previewImage, fileList} = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const num = this.props.num ? this.props.num : 1
    return (
      <div className="clearfix">
        <Upload
          action={uploadUrl}
          name="xfile"
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          // beforeUpload={this.beforeUpload}
        >
          {fileList.length >= num ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{width: '100%'}} src={previewImage}/>
        </Modal>
      </div>
    );
  }
}

export default PUpLodadImg;
